package br.com.serctam.validadores;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.log.Log;

import br.com.caelum.stella.validation.CPFValidator;


@Name("validaCPF") 
@Scope(ScopeType.CONVERSATION)
@org.jboss.seam.annotations.faces.Validator
@BypassInterceptors
public class ValidaCPF implements Validator, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2026978995084253956L;
	
	@Logger
	Log log;
	
	
	public void validate(FacesContext context, UIComponent uiComponent, Object value)
			throws ValidatorException {
		
		if (value == null){
			return;
		}
		
		String cpfValue = null;
		if (value instanceof String) {
			cpfValue = (String) value;
			
		} else {
			return;
		}
		
		try {
			//Valida tamanho e mascara
			String reg = "[0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}";
			if(!cpfValue.matches(reg)){
				throw new Exception();
			}

			//Valida digito
			//String cpfSemMascara = cpfValue.replaceAll("\\.", "").replaceAll("-", "");
			CPFValidator cpfValidator = new CPFValidator(true);
			cpfValidator.assertValid(cpfValue);
		} catch (Exception e) {
			throw new ValidatorException(new FacesMessage("CPF invalido"));
		
		}
	}

}
